package manager;

import android.app.Dialog;

import com.peng.auctionsystem.R;

import Widget.LoadingDialog;
import base.BaseActivity;
import base.BaseApplication;
import rx.Subscriber;
import utils.NetWorkUtils;

/**
 * Created by Mr.Q on 2018/3/30.
 * 描述
 */

public abstract class RxSubscriber<T> extends Subscriber<T> {

    private BaseActivity mActivity;
    private String msg;
    private boolean showDialog=true;
    private boolean cancelable = true;
    private Dialog mDialog;

    /**
     * 是否显示浮动dialog
     */
    public void showDialog() {
        this.showDialog= true;
    }
    public void hideDialog() {
        this.showDialog= true;
    }

    public RxSubscriber(BaseActivity context, String msg, boolean showDialog, boolean cancelable) {
        this.mActivity = context;
        this.msg = msg;
        this.showDialog=showDialog;
        this.cancelable = cancelable;
    }
    public RxSubscriber(BaseActivity context, boolean showDialog, boolean cancelable) {
        this(context, BaseApplication.getAppContext().getString(R.string.loading), showDialog, cancelable);
    }

    /**
     * 不显示dialg
     * @param context
     */
    public RxSubscriber(BaseActivity context) {
        this(context,BaseApplication.getAppContext().getString(R.string.loading), false, false);
    }


    @Override
    public void onCompleted() {
        if (mDialog != null) {
            mDialog.cancel();
            mDialog = null;
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        if (showDialog) {
            try {
                mDialog =  LoadingDialog.showDialogForLoading(mActivity,msg,cancelable);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onNext(T t) {
        _onNext(t);

    }
    @Override
    public void onError(final Throwable e) {
        //防止网络异常时chain.proceed(request)抛出异常，回调在子线
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mDialog != null) {
                    mDialog.cancel();
                    mDialog = null;
                }
                e.printStackTrace();
                //无网络
                if (!NetWorkUtils.isNetConnected(BaseApplication.getAppContext())) {
                    _onError("无网络连接");
                }
                //服务器
                else if (e instanceof ApiException) {

                    _onError(((ApiException) e).getErrorMessage());
                }
                else {
                    _onError("error:" + e.getLocalizedMessage() + " Please check!");
                }
            }
        });


    }

    protected abstract void _onNext(T t);

    protected abstract void _onError(String message);

}

